package com.atguigu.flow.service.impl;

import com.atguigu.flow.entity.IwFlow;
import com.atguigu.flow.entity.IwInstance;
import com.atguigu.flow.entity.IwTask;
import com.atguigu.flow.mapper.IwInstanceMapper;
import com.atguigu.flow.mapper.IwTaskMapper;
import com.atguigu.flow.mapper.SqlMapper;
import com.atguigu.flow.service.IwInstanceService;
import com.atguigu.flow.utils.DateUtil;
import com.atguigu.flow.utils.GetFlowModule_field_util;
import com.atguigu.flow.utils.Workflow;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-03-01
 */
@Service
public class IwInstanceServiceImpl extends ServiceImpl<IwInstanceMapper, IwInstance> implements IwInstanceService {


    @Autowired
    private IwTaskMapper iwTaskMapper;
    @Autowired
    private  SqlMapper sqlMapper;


    @Autowired
    GetFlowModule_field_util getFlowModule_field_util;

    private static final Logger logapp = LoggerFactory.getLogger("applog");

    @Override
    public
    String flow_agree(String recordid, String modulename,Boolean isagree,String... arr) throws Exception {
        String username="";
        String content="";
        String userid="";
        String datestr="";
        if (arr.length>0)
             username=arr[0];
        if (arr.length>1) content=arr[1];
        if (arr.length>2) datestr=arr[2];
        //System.out.println(username);
        Boolean isrole=sqlMapper.getrole(username,"Administrators");
        if (!isrole) {
            userid = sqlMapper.get_userid(username);
            if (StringUtils.isEmpty(userid)) {
                return "用户:" + username + "不存在";
            }
        }

        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
//        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
//        String modulename = "赊销额度申请";
        wrapper.select("top 1 * ");
        wrapper.eq("RecordID", recordid)
                .eq("Module", modulename)
                .eq("Deleted", 0)
                .isNull("FinishTime")
                .ne("State", 2);

        //.orderByDesc("serialid");
        Integer flowupdatecount=0;
        Integer taskinscount=0;
        Integer taskupdatecount=0;
        Integer updatemaintablecount=0;
        String save_result="";
        String unitname="";

        Integer count = baseMapper.selectCount(wrapper);
        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
        Map<String, Object> params = new HashMap<>();
        if (count > 0) {
            wrapper.orderByDesc("serialid");
            IwInstance iwInstance = baseMapper.selectOne(wrapper);
            QueryWrapper<IwTask> taskQueryWrapper = new QueryWrapper<>();
            taskQueryWrapper.select("top 1 * ");
            taskQueryWrapper.eq("InstanceID", iwInstance.getInstanceID());
            taskQueryWrapper.eq("Deleted", 0);

            taskQueryWrapper.orderByDesc("serialid");
            List<IwTask>iwTaskList =iwTaskMapper.selectList(taskQueryWrapper);
            if (iwTaskList.size()==0){
                logapp.info(save_result);
                save_result="无相应的审批任务";
                return save_result;

            }
            IwTask iwTask = iwTaskList.get(0);


                if (!StringUtils.isEmpty(userid)&&
                        !iwTask.getExecutor().equals(userid)){
                    return username+"没有审批任务";

            }

            //System.out.println(iwTask);


            String xml = iwInstance.getFlowData();
            //System.out.println(xml);
            Document doc = null;
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
//            System.out.println("1--"+rootElt.getDocument());
            //System.out.println("2--"+rootElt.asXML());
            params.clear();
            params.put("Content",content);
            Workflow.module_arraylist=Workflow.getmodle_fieldlist(modulename);
            Date spectime=new Date();
            if (!StringUtils.isEmpty(datestr))
                spectime =DateUtil.formatdatetime(datestr);
            else
                spectime=new Date();
            getFlowModule_field_util.ative_elemnt(recordid, modulename,content, rootElt, isagree, params,spectime);
            Document document = DocumentHelper.parseText(rootElt.asXML());

            if (!StringUtils.isEmpty(params) && params.size() > 0) {
                iwInstance.setCurrentFlowActivity(params.get("CurrentFlowActivity").toString());
                iwInstance.setLastFlowActivity(params.get("LastFlowActivity").toString());
                //iwInstance.setTaskid(params.get("TaskID").toString());
                if (params.get("CurrentFlowActivity").toString().equals("已结束")) {
                    iwInstance.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
                    iwInstance.setState(2);
                }

                unitname=params.get("CurrentFlowActivity").toString();
                iwInstance.setFlowData(document.asXML());
                flowupdatecount = baseMapper.update_flowdata(iwInstance);
                //System.out.println("流程表更新" + Integer.valueOf(flowupdatecount));
                //System.out.println(count);
                String filepath = "d:\\xml/("+recordid+")" + params.get("unitname").toString() + ".xml";
                OutputFormat outputFormat = new OutputFormat();
                outputFormat.setEncoding("UTF-8");
                OutputStream outputStream = null;
                outputStream = new FileOutputStream(filepath);
                XMLWriter xmlWriter = new XMLWriter(outputStream, outputFormat);

                xmlWriter.write(document);

//                //检测是否存在该目录
//                if (!dest.getParentFile().exists()) {
//                    dest.getParentFile().mkdirs();
//                }
//                XMLWriter write = new XMLWriter(
//                        new FileWriter(filepath)
//                );
//                write.write(document);
//                write.close();
                System.out.println(params);
                if (!StringUtils.isEmpty(iwTask)) {
//                    if (!params.containsKey("endflow")){
                    iwTask.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
                    iwTask.setState(Integer.valueOf(params.get("State").toString()));
                    iwTask.setContent(params.get("Content").toString());
                    taskupdatecount = iwTaskMapper.update_flowdata(iwTask);
                    System.out.println("任务表更新" + Integer.valueOf(taskupdatecount));
//                    if (!params.get("CurrentFlowActivity").toString().equals("EndUnit")){
                    if (!params.containsKey("endflow")) {
                        iwTask.setSerialID(null);
                        iwTask.setTaskID(params.get("TaskID").toString());
                        iwTask.setUnitName(params.get("unitname").toString());
                        iwTask.setExecutor(params.get("Executor").toString());
                        iwTask.setState(0);
                        iwTask.setFinishTime(null);
                        iwTask.setContent(null);
                        iwTask.setReceiveTime(DateUtil.StringTodatetime((params.get("ReceiveTime").toString())));
                        iwTask.setSubject(params.get("subject").toString());
                        iwTask.setDeleted(false);
                        taskinscount = iwTaskMapper.insert(iwTask);
                        System.out.println("任务表新增" + Integer.valueOf(taskinscount));


                    }
                    else{
                        updatemaintablecount=getFlowModule_field_util.DoAfterFinish(modulename,recordid);
                        System.out.println(updatemaintablecount);}


                }
//                System.out.println(params);
//                System.out.print(iwInstance);
//                System.out.print(iwTask);

            }
            save_result="当前审批节点:"+unitname+"/流程表更新:"+String.valueOf(flowupdatecount)+"/任务表更新:"+String.valueOf(taskupdatecount)+"/任务表新增:"+String.valueOf(taskinscount)+"/更新"+modulename+"状态:"+String.valueOf(updatemaintablecount);


        }
        else
            save_result="当前无审批记录，请确认流程是否启动或已完成";


        //System.out.println(document.asXML());
        //System.out.println(getFlowModule_field_util.sybjl("赊销额度申请","jlsp","钱临波2"));
        //写入emp1.xml文件
        //writerDocumentToNewFile(document);


        //System.out.println(str);

        logapp.info(save_result);
        return save_result;
    }

    @Override
    public
    Boolean changeusr(String recordid, String modulename,  String olduser, String newuser) throws DocumentException {
       Boolean isupdate=false;
        String olduserid=sqlMapper.get_userid(olduser);
       String newuserid=sqlMapper.get_userid(newuser);
       if (!StringUtils.isEmpty(olduserid)& !StringUtils.isEmpty(newuserid)) {
           QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
//        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
//        String modulename = "赊销额度申请";
           //wrapper.select("top 1 * ");
           wrapper.eq("RecordID", recordid)
                   .eq("Module", modulename);
           List<IwInstance> iwInstanceList = baseMapper.selectList(wrapper);
           for (IwInstance iwInstance : iwInstanceList) {
               String xml = iwInstance.getFlowData();
               //System.out.println(xml);
               Document doc = null;
               doc = DocumentHelper.parseText(xml);
               Element rootElt = doc.getRootElement();
               Boolean ischange = getFlowModule_field_util.changeusr(rootElt, olduserid, newuserid);
               if (ischange) {
                   Document document = DocumentHelper.parseText(rootElt.asXML());
                   iwInstance.setFlowData(document.asXML());
                   String instanceid=iwInstance.getInstanceID();
                   int updatecout = baseMapper.update_onlyflowdata(iwInstance);
                   System.out.println(instanceid);
                   //UpdateWrapper<IwTask> updateWrapper = new UpdateWrapper<>();
                   Map<String, Object> map = new HashMap<String, Object>();
                   map.put("newuserid",newuserid);
                   map.put("olduserid",olduserid);
                   map.put("instanceid",instanceid);

                   iwTaskMapper.update_executor(map);
                   if (updatecout > 0)
                       isupdate = true;


               }


           }
       }
        return isupdate;
    }

}
